<template>
  <div class="main-container">
    <TableBody>
      <template #header>
        <TableHeader ref="tableHeaderRef" :show-filter="false">
          <template #search-content>
            <a-form ref="serchForm" :model="form" :style="{ width: '100%' }">
              <a-row :gutter="24">
                <a-col :span="4">
                  <a-form-item field="planName" hide-label>
                    <a-input v-model="form.planName" placeholder="请输入方案名称" allow-clear />
                  </a-form-item>
                </a-col>
                <!-- <a-col :span="4">
                  <a-form-item field="state" hide-label>
                    <a-select v-model="form.close" placeholder="请选择方案状态" allow-clear>
                      <a-option value="0">正常</a-option>
                      <a-option value="1">关闭</a-option>
                    </a-select>
                  </a-form-item>
                </a-col> -->
                <a-col :span="4">
                  <a-form-item field="addTime" hide-label>
                    <a-date-picker
                      style="width: 100%"
                      v-model="form.addTime"
                      show-time
                      :disabledDate="changeTraceEnd"
                      placeholder="请选择开始创建时间"
                      :shortcuts="[
                        {
                          label: '今日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (form.endTime = $dayjs('23:59:59', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            ))
                          ),
                        },
                        {
                          label: '昨日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs('23:59:59', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '七日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(6, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '本月',
                          value: () => (
                            (form.addTime = $dayjs('01 00:00:00', 'DD HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (form.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '上月',
                          value: () => (
                            (form.addTime = $dayjs(`01 00:00:00`, 'DD HH:mm:ss')
                              .subtract(1, 'month')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs()
                              .subtract(1, 'month')
                              .endOf('month')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                      ]"
                      :time-picker-props="{ defaultValue: '12:00:00' }"
                      format="YYYY-MM-DD HH:mm:ss"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="endTime" hide-label>
                    <a-date-picker
                      style="width: 100%"
                      v-model="form.endTime"
                      show-time
                      :disabledDate="changeTraceStart"
                      placeholder="请选择结束创建时间"
                      :shortcuts="[
                        {
                          label: '今日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (form.endTime = $dayjs('23:59:59', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            ))
                          ),
                        },
                        {
                          label: '昨日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs('23:59:59', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '七日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(6, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '本月',
                          value: () => (
                            (form.addTime = $dayjs('01 00:00:00', 'DD HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (form.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '上月',
                          value: () => (
                            (form.addTime = $dayjs(`01 00:00:00`, 'DD HH:mm:ss')
                              .subtract(1, 'month')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs()
                              .subtract(1, 'month')
                              .endOf('month')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                      ]"
                      :time-picker-props="{ defaultValue: '12:00:00' }"
                      format="YYYY-MM-DD HH:mm:ss"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="btns" hide-label>
                    <a-space :size="15">
                      <a-button
                        type="primary"
                        v-permission="couponList"
                        html-type="submit"
                        @click="doRefresh(1)"
                        ><template #icon>
                          <icon-search />
                        </template>
                        <!-- Use the default slot to avoid extra spaces -->
                        <template #default>搜索</template></a-button
                      >
                      <a-button v-permission="couponList" @click="resetSeach"
                        ><template #icon>
                          <icon-sync theme="outline" size="14" />
                        </template>
                        <!-- Use the default slot to avoid extra spaces -->
                        <template #default>重置</template></a-button
                      >
                    </a-space>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </template>
        </TableHeader>
      </template>
      <template #table-config>
        <a-space :size="15">
          <a-button type="primary" v-permission="couponadd" @click="showAdd">
            <!-- Use the default slot to avoid extra spaces -->
            <template #default>新建</template>
          </a-button>
        </a-space>
        <a-space :size="15">
          <TableConfig
            @update-border="onUpdateBorder"
            @update-striped="onUpdateStriped"
            @refresh="doRefresh"
          />
        </a-space>
      </template>
      <template #default>
        <a-table
          :loading="tableLoading"
          :bordered="{ wrapper: true, cell: tables.bordered }"
          :stripe="(tables.striped as boolean)"
          :data="table.dataList"
          :pagination="false"
          :row-key="rowKey"
          :row-class-name="rowClassNameFun"
        >
          <template #columns>
            <a-table-column
              v-for="item of tableColumns.list"
              :key="item.key"
              align="left"
              :title="(item.title as string)"
              :width="item.width"
              :data-index="(item.key as string)"
              :fixed="item.fixed"
            >
              <template v-if="item.key === 'userRealName'" #cell="{ record }">
                <span v-if="record.userRealName">
                  <a-button style="padding: 0px 4px" type="text" size="small"> 已实名</a-button>
                </span>
                <span v-else>
                  <a-button style="padding: 0px 4px" type="text" size="small">未实名</a-button>
                </span>
              </template>

              <template v-else-if="item.key === 'seriesList'" #cell="{ record }">
                <span style="cursor: pointer" @click="seriesList(record.seriesList)">
                  {{ record.seriesList.length }}</span
                >
              </template>
              <template v-else-if="item.key === 'seriesCouponList'" #cell="{ record }">
                <span style="cursor: pointer"> {{ record.seriesCouponList.length }}</span>
              </template>
              <!-- <template v-else-if="item.key === 'close'" #cell="{ record }">
                <a-switch v-model="record.close" @change="changeState(record)">
                  <template #checked-icon>
                    <icon-check />
                  </template>
                  <template #unchecked-icon>
                    <icon-close />
                  </template>
                </a-switch>
              </template> -->
              <template v-else-if="item.key === 'actions'" #cell="{ record }">
                <a-space :size="2">
                  <a-button
                    v-permission="couponupdate"
                    style="padding: 0px 4px"
                    type="text"
                    size="small"
                    @click="updatUserPop(record)"
                    >编辑</a-button
                  >
                  <a-button
                    v-permission="couponadd"
                    style="padding: 0px 4px"
                    type="text"
                    size="small"
                    @click="onCopy(record)"
                    >复制</a-button
                  >
                  <a-button
                    v-permission="coupon"
                    style="padding: 0px 4px"
                    type="text"
                    size="small"
                    @click="programmeFn(record.id)"
                    >设置</a-button
                  >
                  <a-button
                    v-permission="coupondelete"
                    style="padding: 0px 4px"
                    type="text"
                    size="small"
                    @click="onDeleteItem(record)"
                    >删除</a-button
                  >
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
    </TableBody>
    <a-modal
      v-model:visible="visibleList"
      title="设置优惠券"
      width="800px"
      @before-close="handleList"
      :mask-closable="false"
      title-align="start"
    >
      <div style="margin-bottom: 10px"
        ><a-button v-permission="couponupdate" type="primary" @click="showAdds">
          <!-- Use the default slot to avoid extra spaces -->
          <template #default>新建</template>
        </a-button></div
      >
      <a-table
        :data="programmeList"
        :scroll="{ x: 1000 }"
        :pagination="false"
        @change="handleChange"
        :draggable="{ type: 'handle', width: 40 }"
        :row-key="rowKey"
      >
        <template #columns>
          <a-table-column
            v-for="item of tableColumns1.list"
            :key="item.key"
            align="left"
            :width="item.width"
            :title="(item.title as string)"
            :data-index="(item.key as string)"
            :fixed="item.fixed"
          >
            <template v-if="item.key === 'state'" #cell="{ record }">
              <a-tag color="blue" v-if="record.state == true">正常</a-tag>
              <a-tag color="red" v-else>关闭</a-tag>
            </template>
            <template v-if="item.key === 'actions'" #cell="{ record }">
              <a-space :size="2">
                <a-button
                  v-permission="couponinfosa"
                  style="padding: 0px 4px"
                  type="text"
                  size="small"
                  @click="updatUserPops(record)"
                  >编辑</a-button
                >
                <a-button
                  v-permission="couponadds"
                  style="padding: 0px 4px"
                  type="text"
                  size="small"
                  @click="copyPops(record)"
                  >复制</a-button
                >
                <a-button
                  v-permission="coupondeletes"
                  style="padding: 0px 4px"
                  type="text"
                  size="small"
                  @click="onDeleteItems(record)"
                  >删除</a-button
                >
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
      <template #footer>
        <a-space />
      </template>
    </a-modal>
    <a-modal
      v-model:visible="visible"
      @before-close="handleCancel"
      :title="title"
      width="600px"
      :mask-closable="false"
      title-align="start"
    >
      <a-form ref="userForm" :auto-label-width="true" :model="subForm">
        <a-form-item
          label="方案名称"
          field="planName"
          :rules="[
            { required: true, message: '方案名称不能为空' },
            { minLength: 1, maxLength: 100, message: '方案名称必须小于100个字符' },
          ]"
          asterisk-position="end"
          :validate-trigger="['change', 'input']"
        >
          <a-input v-model.trim="subForm.planName" placeholder="请输入方案名称" allow-clear />
        </a-form-item>
        <a-form-item
          label="券包名称"
          field="couponPackName"
          :rules="[
            { required: true, message: '券包名称不能为空' },
            { minLength: 1, maxLength: 100, message: '券包名称必须小于100个字符' },
          ]"
          asterisk-position="end"
          :validate-trigger="['change', 'input']"
        >
          <a-input v-model.trim="subForm.couponPackName" placeholder="请输入方案名称" allow-clear />
          <template #extra>
            <div>默认名称为优惠券，但是有些客户不想起名为优惠券，可以自己定义名称</div>
          </template>
        </a-form-item>
        <a-form-item label="按钮内容" field="skipButton">
          <a-input v-model.trim="subForm.skipButton" placeholder="请输入按钮内容" allow-clear />
        </a-form-item>
        <a-form-item
          label="限购次数"
          field="buyNumberLimit"
          :rules="[{ required: true, message: '限购次数不能为空' }]"
          asterisk-position="end"
          :validate-trigger="['change', 'input']"
        >
          <a-input-number
            v-model.trim="subForm.buyNumberLimit"
            placeholder="请输入限购次数"
            allow-clear
          />
          <template #extra>
            <div>方案内的优惠券，客户可以买多少次</div>
          </template>
        </a-form-item>
        <a-form-item
          label="加油包"
          field="refuelingBagLimit"
          class="input516"
          :rules="[{ required: true, message: ' ' }]"
          :validate-trigger="['change']"
          asterisk-position="end"
        >
          <a-radio-group class="radio-bcg" v-model="subForm.refuelingBagLimit">
            <a-radio :value="true">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">限制购买</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="false">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">不限制购买</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
          <template #extra>
            <div>限制购买：不可以使用优惠券购买加油包</div>
          </template>
        </a-form-item>
        <a-form-item
          label="优惠提示"
          field="couponTipsState"
          class="input516"
          :rules="[{ required: true, message: ' ' }]"
          :validate-trigger="['change']"
          asterisk-position="end"
        >
          <a-radio-group
            class="radio-bcg"
            @change="changeCouponTipsState"
            v-model="subForm.couponTipsState"
          >
            <a-radio :value="false">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">关闭</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="true">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">开启</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
          <template #extra>
            <div>对于未购买优惠券或者优惠券已经过期的客户，进行优惠提示</div>
          </template>
        </a-form-item>
        <a-form-item
          label="强制购买"
          field="skip"
          class="input516"
          :rules="[{ required: true, message: ' ' }]"
          :validate-trigger="['change']"
          asterisk-position="end"
        >
          <a-radio-group class="radio-bcg" v-model="subForm.skip">
            <a-radio :value="true">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">开启</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="false">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">关闭</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
          <template #extra>
            <div>开启：强制客户购买优惠券</div>
          </template>
        </a-form-item>
        <a-form-item
          label="使用限制"
          field="solaUseLimit"
          class="input516"
          :rules="[{ required: true, message: ' ' }]"
          :validate-trigger="['change']"
          asterisk-position="end"
        >
          <a-radio-group class="radio-bcg" v-model="subForm.solaUseLimit">
            <a-radio :value="true">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">开启</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="false">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">关闭</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
          <template #extra>
            <div>开启后，大于30天或者大于1月的套餐，单次只能使用一张优惠券</div>
          </template>
        </a-form-item>
        <a-form-item
          v-if="subForm.couponTipsState == true"
          label="提示内容"
          field="couponTips"
          :rules="[{ required: true, message: ' ' }]"
          asterisk-position="end"
          :validate-trigger="['change', 'input']"
        >
          <RichTextEditor v-if="visible" v-model="subForm.couponTips" ref="richTextEditor" />
        </a-form-item>
        <a-form-item
          v-if="subForm.id"
          label="展示模式"
          field="couponPackName"
          asterisk-position="end"
          :validate-trigger="['change', 'input']"
        >
          <a-input-group style="width: 100%">
            <a-select
              v-model="subForm.showType"
              placeholder="指定展示优惠券"
              @change="subForm.showCouponId = ''"
            >
              <a-option :value="0">单张优惠券</a-option>
              <a-option :value="1">多张优惠券</a-option>
            </a-select>
            <a-select
              v-if="subForm.showType == 0"
              v-model="subForm.showCouponId"
              placeholder="选择优惠方案"
            >
              <a-option v-for="item in couponLists" :key="item.id" :value="item.id">{{
                item.couponName
              }}</a-option>
            </a-select>
          </a-input-group>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="handleCancel">取消</a-button>
          <a-button type="primary" @click="handleBeforeOk">确定</a-button>
        </a-space>
      </template>
    </a-modal>
    <a-modal
      v-model:visible="addtagvisibles"
      title="应用系列"
      width="600px"
      :mask-closable="false"
      title-align="start"
    >
      <Table :tablist="series" />
      <template #footer>
        <a-space />
      </template>
    </a-modal>
    <a-modal
      v-model:visible="visibles"
      :title="titles"
      width="600px"
      @before-close="handleCancels"
      :mask-closable="false"
      title-align="start"
    >
      <a-form ref="userForms" :auto-label-width="true" :model="subForms">
        <a-form-item
          label="券包名称"
          field="couponName"
          :rules="[
            { required: true, message: '券包名称不能为空' },
            { minLength: 1, maxLength: 100, message: '券包名称必须小于100个字符' },
          ]"
          asterisk-position="end"
          :validate-trigger="['change', 'input']"
        >
          <a-input v-model.trim="subForms.couponName" placeholder="请输入券包名称" allow-clear />
          <template #extra>
            <div>券包名称根据自身需求随意填写</div>
          </template>
        </a-form-item>

        <a-form-item
          label="券包售价"
          field="couponPrice"
          :rules="[{ required: true, message: '券包售价不能为空' }]"
          asterisk-position="end"
          :validate-trigger="['change', 'input']"
        >
          <a-input-number v-model="subForms.couponPrice" placeholder="请输入券包售价" allow-clear />
          <template #extra>
            <div>券包客户购买需要支付的金额，输入100，客户就需要支付100元</div>
          </template>
        </a-form-item>
        <a-form-item
          v-for="(post, index) of subForms.seriesCouponStepList"
          :field="`posts.${index}.value`"
          label="券包设置"
          :key="index"
        >
          <a-input-group style="width: 100%">
            <a-input v-model="post.couponPrice" placeholder="优惠券金额" />
            <a-input v-model="post.couponCount" placeholder="优惠券数量" />
            <a-input v-model="post.sort" placeholder="优惠券排序" />
          </a-input-group>
          <!-- <a-button><a-checkbox v-model="post.recommend">余额推荐 </a-checkbox></a-button> -->
          <i-add
            style="cursor: pointer; margin-left: 10px"
            v-if="index == 0"
            size="18"
            @click="addItem"
          />
          <i-reduce
            style="cursor: pointer; margin-left: 10px"
            v-else
            size="18"
            @click="handleDelete(index)"
          />
          <template #extra>
            <div>优惠券数量：优惠券有多张；优惠券金额：每张优惠券优惠的金额</div>
          </template>
        </a-form-item>
        <a-form-item
          label="余额搭配"
          field="payBalance"
          :rules="[{ required: true, message: '券包售价不能为空' }]"
          asterisk-position="end"
          :validate-trigger="['change', 'input']"
        >
          <a-input-group style="width: 100%">
            <a-input v-model="subForms.payBalance" placeholder="请输入充值金额" />
            <a-input v-model="subForms.giveBalance" placeholder="请输入赠送金额" />
          </a-input-group>
          <template #extra>
            <div
              >输入充值金额后，客户购买优惠券时，需要支付券包售价+充值金额，单独输入赠
              送金额，充值完优惠券直接赠送对应余额</div
            >
          </template>
        </a-form-item>
        <a-form-item
          label="限制售价"
          field="priceLimit"
          :rules="[{ required: true, message: '限制售价不能为空' }]"
          asterisk-position="end"
          :validate-trigger="['change', 'input']"
        >
          <a-input-number v-model="subForms.priceLimit" placeholder="请输入限制售价" allow-clear />
          <template #extra>
            <div>套餐售价低于多少元不可以使用优惠券</div>
          </template>
        </a-form-item>
        <a-form-item label="按钮内容" field="buttonContent">
          <a-input v-model.trim="subForms.buttonContent" placeholder="请输入按钮内容" allow-clear />
          <template #extra>
            <div>底部按钮内显示的文字</div>
          </template>
        </a-form-item>
        <a-form-item
          label="推荐购买"
          field="recommend"
          class="input516"
          :rules="[{ required: true, message: ' ' }]"
          :validate-trigger="['change']"
          asterisk-position="end"
        >
          <a-radio-group class="radio-bcg" v-model="subForms.recommend">
            <a-radio :value="true">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">开启</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="false">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">关闭</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
          <template #extra>
            <div>套餐售价低于多少元不可以使用优惠券</div>
          </template>
        </a-form-item>
        <a-form-item
          label="券包状态"
          field="state"
          class="input516"
          :rules="[{ required: true, message: ' ' }]"
          :validate-trigger="['change']"
          asterisk-position="end"
        >
          <a-radio-group class="radio-bcg" v-model="subForms.state">
            <a-radio :value="true">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">正常</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="false">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">关闭</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          label="详细介绍"
          field="couponInfo"
          :rules="[{ required: true, message: ' ' }]"
          asterisk-position="end"
          :validate-trigger="['change', 'input']"
        >
          <RichTextEditor v-if="visibles" v-model="subForms.couponInfo" ref="richTextEditors" />
        </a-form-item>
        <a-form-item label="券包图片" field="couponImg">
          <a-upload
            action="/app/file/upload"
            :show-file-list="false"
            @success="onSuccessBcg"
            :image-preview="true"
          >
            <template #upload-button>
              <div class="arco-upload-list-picture custom-upload-avatar" v-if="subForms.couponImg">
                <img :src="subForms.couponImg" />
                <div class="arco-upload-list-picture-mask">
                  <IconEdit />
                </div>
              </div>
              <div class="arco-upload-picture-card" v-else>
                <div class="arco-upload-picture-card-text">
                  <IconPlus />
                </div>
              </div>
              <!-- </div> -->
            </template>
          </a-upload>
        </a-form-item>
        <a-form-item label="余额图片" field="balanceImg">
          <a-upload
            action="/app/file/upload"
            :show-file-list="false"
            @success="onSuccessLogo1"
            :image-preview="true"
          >
            <template #upload-button>
              <div class="arco-upload-list-picture custom-upload-avatar" v-if="subForms.balanceImg">
                <img :src="subForms.balanceImg" />
                <div class="arco-upload-list-picture-mask">
                  <IconEdit />
                </div>
              </div>
              <div class="arco-upload-picture-card" v-else>
                <div class="arco-upload-picture-card-text">
                  <IconPlus />
                </div>
              </div>
              <!-- </div> -->
            </template>
          </a-upload>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="handleCancels">取消</a-button>
          <a-button :loading="btnLoadings" type="primary" @click="handleBeforeOks">确定</a-button>
        </a-space>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import useCommonStore from '@/store/modules/common'
  import * as http from '@/api/http'
  import Table from '@/views/polling/compoents/table.vue'
  import {
    couponList,
    couponadd,
    couponupdate,
    coupondelete,
    coupons,
    coupon,
    couponadds,
    couponupdates,
    coupondeletes,
    couponinfosa,
    couponSort,
  } from '@/api/url'
  import { useRowKey, useTable } from '@/hooks/table'
  import { Form, Message, Modal } from '@arco-design/web-vue'
  import { onMounted, reactive, ref } from 'vue'
  const useCommon = useCommonStore()
  const table = useTable()
  const visibleList = ref(false)
  const rowKey = useRowKey('id')
  const visible = ref(false)
  const userForms = ref()
  const subForms = ref({
    couponName: '',
    couponPrice: '',
    payBalance: '',
    giveBalance: '',
    priceLimit: '',
    couponInfo: '',
    couponImg: '',
    balanceImg: '',
    state: true,
    recommend: true,
    planId: '',
    buttonContent: '',
    seriesCouponStepList: [
      {
        couponPrice: '', //充值金额
        sort: '', //赠送金额
        couponCount: '', //是否推荐 true推荐, false不推荐
      },
    ], //预存金额充值列表
  })
  const visibles = ref(false)
  const btnLoading = ref(false)
  const addtagvisibles = ref(false)
  const userForm = ref<typeof Form>()
  const form = reactive({
    planName: '',
    addTime: '',
    endTime: '',
  })
  const tableColumns1: any = reactive({
    list: [
      {
        title: '优惠券名称',
        key: 'couponName',
        dataIndex: 'couponName',
        width: 100,
      },
      {
        title: '售价',
        key: 'couponPrice',
        dataIndex: 'couponPrice',
        width: 50,
      },
      {
        title: '数量',
        key: 'couponCount',
        dataIndex: 'couponCount',
        width: 50,
      },
      {
        title: '优惠金额',
        key: 'price',
        dataIndex: 'price',
        width: 50,
      },
      {
        title: '状态',
        key: 'state',
        dataIndex: 'state',
        width: 50,
      },
      {
        title: '创建时间',
        key: 'addTime',
        dataIndex: 'addTime',
        width: 190,
      },
      {
        title: '操作',
        key: 'actions',
        dataIndex: 'actions',
        width: 80,
        fixed: 'right',
      },
    ],
  })
  const series = ref([])
  const programmeList = ref([])
  const id = ref('')
  const couponLists: any = ref([])
  const subForm: any = ref({
    id: '',
    planName: '',
    skipButton: '',
    couponPackName: '优惠券',
    buyNumberLimit: 0, //限购次数(方案内的优惠券，客户可以买多少次)，0不限制
    refuelingBagLimit: true, //加油包使用限制 0不限制，1限制使用，默认0
    couponTipsState: false, //优惠提示(对未购买、已过期的进行提示)，0关闭，1开启，默认0
    couponTips: '',
    skip: true, //强制购买 0关闭 1开启，默认0
    showType: 1, //  展示模式 0单张 1多张，默认1
    showCouponId: '',
    solaUseLimit: false, //使用限制0关闭 1开启，默认0
  })
  const tableColumns: any = reactive({
    list: [
      {
        title: '方案名称',
        key: 'planName',
        dataIndex: 'planName',
        checked: true,
        width: 351,
      },
      {
        title: '优惠券数量',
        key: 'seriesCouponList',
        dataIndex: 'seriesCouponList',
        checked: true,
        width: 260,
      },
      {
        title: '应用系列',
        key: 'seriesList',
        dataIndex: 'seriesList',
        checked: true,
        width: 260,
      },
      // {
      //   title: '方案状态',
      //   key: 'close',
      //   dataIndex: 'close',
      //   checked: true,
      // },
      {
        title: '创建时间',
        key: 'addTime',
        dataIndex: 'addTime',
        checked: true,
        width: 190,
      },
      {
        title: '操作',
        key: 'actions',
        fixed: 'right',
        dataIndex: 'actions',
        width: 330,
        align: 'center',
        checked: true,
      },
    ],
  })
  const richTextEditor = ref()
  const richTextEditors = ref()
  const tableLoading = ref(false)
  const btnLoadings = ref(false)
  const tables = reactive({
    tableLoading: false,
    bordered: false,
    striped: false,
    expand: [1],
    isExpand: false,
  })
  const title = ref('')
  function showAdd() {
    subForm.value.id = ''
    title.value = '新建方案'
    userForm.value?.resetFields()
    visible.value = true
  }
  const titles = ref('')
  function showAdds() {
    titles.value = '新建优惠券'
    userForms.value?.resetFields()
    visibles.value = true
  }
  function handleCancels() {
    subForms.value.id = ''
    subForms.value = {
      couponName: '',
      couponPrice: '',
      payBalance: '',
      giveBalance: '',
      priceLimit: '',
      couponInfo: '',
      couponImg: '',
      balanceImg: '',
      state: true,
      recommend: true,
      planId: '',
      buttonContent: '',
      seriesCouponStepList: [
        {
          couponPrice: '', //充值金额
          sort: '', //赠送金额
          couponCount: '', //是否推荐 true推荐, false不推荐
        },
      ], //预存金额充值列表
    }
    visibles.value = false
  }
  function changeSkip() {
    subForm.value.couponTips = ''
  }
  function programmeFn(val: any) {
    id.value = val
    http
      .get({
        url: coupon,
        data: () => {
          return {
            planId: val,
          }
        },
      })
      .then((res) => {
        if (res.code == 0) {
          res.data.forEach((item: any) => {
            if (item.seriesCouponStepList.length > 0) {
              item.price = 0
              item.seriesCouponStepList.forEach((items: any) => {
                item.price = item.price + items.couponPrice
              })
            } else {
              item.price = 0
            }
          })
          programmeList.value = res.data
          visibleList.value = true
        }
      })
      .catch(console.log)
    // visibleList.value = true
  }

  const addItem = () => {
    // if (subForm.value.rechargeRules.length >= 6) {
    //   Message.error('已达最大限制6条')
    //   return false
    // }
    subForms.value.seriesCouponStepList.push({
      couponPrice: '', //充值金额
      sort: '', //排序
      couponCount: '', //数量
    })
  }
  const handleDelete = (index: any) => {
    subForms.value.seriesCouponStepList.splice(index, 1)
  }

  function handleCancel() {
    userForm.value?.resetFields()
    visible.value = false
  }

  const serchForm = ref()
  const resetSeach = () => {
    serchForm.value.resetFields()
    doRefresh(1)
  }
  const handleChange = (_data, extra) => {
    console.log(_data)
    console.log(extra.dragTarget.id)
    var sorts = []
    _data.forEach((item, index) => {
      sorts.push({
        id: item.id,
        sort: index,
      })
      // item.sort = index
    })
    http
      .post({
        url: couponSort,
        data: sorts,
      })
      .then((res) => {
        if (res.code == 0) {
          Message.success(res.msg)
          http
            .get({
              url: coupon,
              data: () => {
                return {
                  planId: extra.dragTarget.planId,
                }
              },
            })
            .then((res) => {
              if (res.code == 0) {
                res.data.forEach((item: any) => {
                  if (item.seriesCouponStepList.length > 0) {
                    item.price = 0
                    item.seriesCouponStepList.forEach((items: any) => {
                      item.price = item.price + items.couponPrice
                    })
                  } else {
                    item.price = 0
                  }
                })
                programmeList.value = res.data
                visibleList.value = true
              }
            })
            .catch(console.log)
        } else {
          Message.error(res.msg)
        }
      })
  }
  function updatUserPop(item: any) {
    title.value = '编辑方案'
    subForm.value = JSON.parse(JSON.stringify(item))
    http
      .get({
        url: coupons,
        data: () => {
          return {
            planId: item.id,
          }
        },
      })
      .then((res) => {
        if (res.code == 0) {
          couponLists.value = res.data
          visible.value = true
        }
      })
      .catch(console.log)
  }

  function updatUserPops(item: any) {
    titles.value = '编辑优惠券'
    http
      .get({
        url: couponinfosa,
        data: () => {
          return {
            couponId: item.id,
          }
        },
      })
      .then((res) => {
        if (res.code == 0) {
          subForms.value = res.data
          visibles.value = true
        }
      })
      .catch(console.log)
  }

  function seriesList(val: any) {
    series.value = val
    addtagvisibles.value = true
  }
  function copyPops(item: any) {
    http
      .get({
        url: couponinfosa,
        data: () => {
          return {
            couponId: item.id,
          }
        },
      })
      .then((res) => {
        if (res.code == 0) {
          subForms.value = res.data
        }
      })
      .catch(console.log)
    Modal.warning({
      title: '操作确认',
      content: '确定要复制此优惠券吗？',
      cancelText: '取消',
      titleAlign: 'start',
      hideCancel: false,
      okText: '复制',
      onOk: () => {
        http
          .post({
            url: couponadds,
            data: () => {
              return {
                ...subForms.value,
              }
            },
          })
          .then((res) => {
            if (res.code == 0) {
              Message.success(res.msg)
              handleCancels()
              listFn(id.value)
            } else {
              Message.error(res.msg)
            }
          })
          .catch(console.log)
      },
    })
  }

  function onDeleteItems(item: any) {
    Modal.warning({
      title: '操作确认',
      content: '确定要删除此优惠券吗？',
      cancelText: '取消',
      titleAlign: 'start',
      hideCancel: false,
      okText: '删除',
      onOk: () => {
        http
          .get({
            url: coupondeletes,
            data: () => {
              return {
                id: item.id,
              }
            },
          })
          .then((res) => {
            if (res.code == 0) {
              Message.success(res.msg)
              listFn(id.value)
            } else {
              Message.error(res.msg)
            }
          })
          .catch(console.log)
      },
    })
  }
  function onDeleteItem(item: any) {
    Modal.warning({
      title: '操作确认',
      content: '确定要删除此方案吗？',
      cancelText: '取消',
      titleAlign: 'start',
      hideCancel: false,
      okText: '删除',
      onOk: () => {
        http
          .get({
            url: coupondelete,
            data: () => {
              return {
                id: item.id,
              }
            },
          })
          .then((res) => {
            if (res.code == 0) {
              Message.success(res.msg)
              doRefresh()
            } else {
              Message.error(res.msg)
            }
          })
          .catch(console.log)
      },
    })
  }
  function listFn(val: any) {
    http
      .get({
        url: coupon,
        data: () => {
          return {
            planId: val,
          }
        },
      })
      .then((res) => {
        if (res.code == 0) {
          res.data.forEach((item: any) => {
            if (item.seriesCouponStepList.length > 0) {
              item.price = 0
              item.seriesCouponStepList.forEach((items: any) => {
                item.price = item.price + items.couponPrice
              })
            } else {
              item.price = 0
            }
          })
          programmeList.value = res.data
          visibleList.value = true
        }
      })
      .catch(console.log)
  }
  function handleBeforeOks() {
    console.log(subForm)
    subForms.value.planId = id.value
    userForms.value?.validate().then((error: any) => {
      if (!error) {
        btnLoadings.value = true
        if (!subForms.value.id) {
          http
            .post({
              url: couponadds,
              data: () => {
                return {
                  ...subForms.value,
                }
              },
            })
            .then((res) => {
              btnLoadings.value = false
              if (res.code == 0) {
                Message.success(res.msg)
                handleCancels()
                listFn(id.value)
              } else {
                Message.error(res.msg)
              }
            })
        } else {
          http
            .post({
              url: couponupdates,
              data: () => {
                return {
                  ...subForms.value,
                }
              },
            })
            .then((res) => {
              btnLoadings.value = false
              if (res.code == 0) {
                Message.success(res.msg)
                handleCancels()
                listFn(id.value)
              } else {
                Message.error(res.msg)
              }
            })
        }
      }
    })
  }
  function handleList() {
    doRefresh()
    visibleList.value = false
  }
  function onCopy(item: any) {
    Modal.warning({
      title: '操作确认',
      content: '确定要复制方案吗？',
      cancelText: '取消',
      titleAlign: 'start',
      hideCancel: false,
      okText: '确认',
      onOk: () => {
        http
          .post({
            url: couponadd,
            data: () => {
              return {
                ...item,
              }
            },
          })
          .then((res) => {
            btnLoading.value = false
            if (res.code == 0) {
              Message.success('复制成功')
              visible.value = false
              userForm.value?.resetFields()
              doRefresh()
            } else {
              Message.error(res.msg)
            }
          })
      },
    })
  }
  function handleBeforeOk() {
    console.log(subForm)
    userForm.value?.validate().then((error: any) => {
      if (!error) {
        if (!subForm.value.id) {
          http
            .post({
              url: couponadd,
              data: () => {
                return {
                  ...subForm.value,
                }
              },
            })
            .then((res) => {
              btnLoading.value = false
              if (res.code == 0) {
                Message.success(res.msg)
                visible.value = false
                subForm.value.id = null
                userForm.value?.resetFields()
                doRefresh()
              } else {
                Message.error(res.msg)
              }
            })
        } else {
          http
            .post({
              url: couponupdate,
              data: () => {
                return {
                  ...subForm.value,
                }
              },
            })
            .then((res) => {
              btnLoading.value = false
              if (res.code == 0) {
                Message.success(res.msg)
                visible.value = false
                subForm.value.id = null
                userForm.value?.resetFields()
                doRefresh()
              } else {
                Message.error(res.msg)
              }
            })
        }
      }
    })
  }
  // function changeState(item: any) {
  //   console.log(item)
  //   http
  //     .get({
  //       url: setRecharge,
  //       data: () => {
  //         return {
  //           close: item.close,
  //           id: item.id,
  //         }
  //       },
  //     })
  //     .then((res) => {
  //       if (res.code == 0) {
  //         Message.success(res.msg)
  //         doRefresh()
  //       } else {
  //         Message.error(res.msg)
  //       }
  //     })
  // }
  function changeCouponTipsState() {
    subForm.value.couponTips = ''
  }
  function doRefresh(value?: number) {
    // eslint-disable-next-line prettier/prettier
    tableLoading.value = true
    if (value) {
    }
    http
      .get({
        url: couponList,
        data: () => {
          return {
            ...form,
          }
        },
      })
      .then((res) => {
        tableLoading.value = false
        table.handleSuccess(res.data)
      })
      .catch(console.log)
  }

  const onUpdateBorder = (isBordered: boolean) => {
    tables.bordered = isBordered
  }
  function onUpdateStriped(isStriped: boolean) {
    tables.striped = isStriped
  }
  function rowClassNameFun(_record: any, index: number) {
    return index % 2 === 1 && table.striped.value ? 'table-striped' : null
  }

  //背景图上传
  const onSuccessBcg = (fileItem: any) => {
    subForms.value.couponImg = fileItem.response.data.path
  }
  //Logo上传
  const onSuccessLogo1 = (fileItem: any) => {
    subForms.value.balanceImg = fileItem.response.data.path
  }
  //跟踪API开始时间限制结束时间
  function changeTraceEnd(time: any) {
    return time.getTime() > new Date(form.endTime).getTime() //大于结束时间的不选
  }
  //跟踪API结束时间限制开始时间
  function changeTraceStart(time: any) {
    return time.getTime() < new Date(form.addTime).getTime() //小于开始时间的不选
  }
  onMounted(async () => {
    doRefresh()
  })
</script>

<style lang="less" scoped>
  :deep(.arco-table-td-content button) {
    padding: 0px !important;
    margin-right: 8px;
    background: none !important;
  }
  .top {
    margin-bottom: 20px;
    background-color: var(--color-bg-1);
    border-radius: 10px;

    .box {
      display: flex;
      align-items: center;
      height: 30px;
      margin: 5px 10px;

      .line {
        width: 5px;
        height: 25px;
        margin-right: 10px;
        background-color: #40a1ff;
      }

      .text {
        font-size: 16px;
        line-height: 25px;
        text-align: center;
      }
    }

    .flex {
      display: flex;
      justify-content: space-around;
      margin: 12px 7px;
      .dataBox:last-child {
        margin-right: 0px !important;
      }
      .dataBox {
        display: flex;
        align-items: center;
        justify-content: center;
        align-items: center;
        flex: 1;
        margin-right: 20px;
        height: 150px;
        background-image: linear-gradient(rgb(var(--arcoblue-1)), #fff);
        border: 1px solid #f2f3f5;
        border-radius: 10px;

        .img {
          width: 70px;
          height: 70px;
          margin-right: 20px;
          border-radius: 50%;
        }

        .name {
          margin-top: 0;
        }

        .number {
          font-size: 22px;
        }
      }
    }
  }
  .avatar-container {
    position: relative;
    width: 30px;
    height: 30px;
    margin: 0 auto;
    vertical-align: middle;
    .avatar {
      width: 100%;
      height: 100%;
      border-radius: 50%;
    }
    .avatar-vip {
      border: 2px solid #cece1e;
    }
    .vip {
      position: absolute;
      top: 0;
      right: -9px;
      width: 15px;
      transform: rotate(60deg);
    }
  }
  .gender-container {
    .gender-icon {
      width: 20px;
    }
  }
  .custom-checkbox-card {
    padding: 5px 16px;
    border-radius: 4px;
    width: auto;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    background-color: var(--color-fill-2);
  }

  .custom-checkbox-card-mask {
    height: 14px;
    width: 14px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 2px;
    border: 1px solid var(--color-border-2);
    box-sizing: border-box;
  }

  .custom-checkbox-card-mask-dot {
    width: 8px;
    height: 8px;
    border-radius: 2px;
  }

  .custom-checkbox-card-title {
    color: var(--color-text-1);
    font-size: 14px;
  }

  .custom-checkbox-card:hover,
  .custom-checkbox-card-checked,
  .custom-checkbox-card:hover .custom-checkbox-card-mask,
  .custom-checkbox-card-checked .custom-checkbox-card-mask {
    border-color: rgb(var(--primary-6));
  }

  .custom-checkbox-card:hover .custom-checkbox-card-title,
  .custom-checkbox-card-checked .custom-checkbox-card-title {
    color: rgb(var(--primary-6));
  }

  .custom-checkbox-card-checked .custom-checkbox-card-mask-dot {
    background-color: rgb(var(--primary-6));
  }
</style>
<style scoped>
  .ant-table-striped :deep(.table-striped) td {
    background-color: #fafafa;
  }
</style>
